<template>
	<view class="content pc-tou-gao " >
		<view class="scroll-fix" >

		
			<view class="d-kuan-juzhong ">
				<!--头部-->
				<view class="d-kuan pc-dingbu " style="z-index: 100" >
					<DToubu 
					@login-success="handleLoginSuccess" 
					:dengluxianshi="denglu_xianshi"
					@update-dengluxianshi="handleUpdateDengluxianshi"
					></DToubu>
				</view>


				<!--头部-->
				<!--下面内容-->
				<view class="d-kuan d-xuanze-0">
					<link href="static/css/wangeditor-style.css" rel="stylesheet" />
					<view class="d-kuan d-shangxia-10">
						<uv-input customStyle="background-color: white;" placeholder="请输入内容" border="surround" v-model="neirong_data.title"></uv-input>
					</view>
					<view class="d-kuan d-shangxia-10">
						<uv-divider text="公开" textPosition="left"></uv-divider>
						<uv-radio-group v-model="neirong_data.gongkai" placement="row">
							<uv-radio name="1" label="正常"></uv-radio>
							<uv-radio class="d-zuo-10" name="0" activeColor="red" label="关闭"></uv-radio>
						</uv-radio-group>
						<uv-divider text="模式" textPosition="left"></uv-divider>
						<uv-radio-group v-model="neirong_data.moshi" placement="row">
							<uv-radio name="1" label="付费"></uv-radio>
							<uv-radio class="d-zuo-10" name="0" activeColor="red" label="免费"></uv-radio>
						</uv-radio-group>
					</view>

					<Toolbar
						style="z-index: 99999"
						:editor="editorRef"
						:defaultConfig="toolbarConfig"
						:mode="mode"
					/>
					
					<Editor
						:style="{ height: leftNavHeight }"
						v-model="valueHtml"
						:defaultConfig="editorConfig"
						:mode="mode"
						@onCreated="handleCreated"
						@onChange="handleChange"
						@onFocus="handleFocus"

					>
					    

					</Editor>
					
					<!--选择圈子-->
					<view v-if="quanzizhi==1" class="d-kuan d-xuanze-1" :style="{height: xuanzequan_gao}">
						<view>
							<uv-tabs :list="quan_daohang_list" @click="yiji2" lineColor="#07bfa6" :activeStyle="{ color: '#0a9a87' }"></uv-tabs>
							<uv-tabs v-if="quan_daohang_list.length > 0 " :key="'erji-' + activeIndex.id"  :current="xuanzezhi" :list="erjidata" @click="erji2" lineColor="#07bfa6" :activeStyle="{ color: '#0a9a87' }"></uv-tabs>
                            <uv-row :customStyle="{ 'margin-top': '20px', 'flex-wrap': 'wrap','margin-left':'5px','margin-right':'5px' }"  :gutter="20" wrap>


									<uv-col v-for="(list,index) in quan_list" span="12">
										<view class="beijing-140 d-kuan d-buhuanhang d-xia-20" @click="quan(list.id,list.title)">

											<!--图片-->
											<view class="d-zuo d-tu-kuan-140 d-piaofu-0">
												<!--view v-if="list.moshi==0" class="d-piaofu-1">免费</view>
												<view v-else class="d-piaofu-1">付费</view-->
												<uv-image :src="list.thumb" width="130rpx" height="130rpx" radius="50"></uv-image>
											</view>
											<view class="d-kuan d-neikuang-10">
												<view class="d-chaochu-1 d-jiacu">{{list.title}}</view>
												<view class="d-chaochu-1 d-ziti-12 d-wenzi-yanse-hui d-shangxia-5">
													{{list.description}}
												</view>
												<view class="d-chaochu-1 d-ziti-12 d-wenzi-yanse-hui d-shangxia-10">
													<uv-icon name="arrow-right" color="#a7a7a7" labelColor="#a7a7a7" size="10" :label="list.catname"></uv-icon>
												</view>

											</view>
											<view class="d-neikuang-10">
												<uv-button customStyle="margin-top: 20px;width: 80px" size="small" :plain="true" type="primary" shape="circle"  text="选择"></uv-button>
											</view>
										</view>


									</uv-col>
									<!-- 加载状态提示 -->
  									<view class="d-kuan d-juzhong d-shangxia-20" v-if="isLoading">
  									  <uv-loading></uv-loading>
  									</view>
  									<view class="d-kuan d-juzhong d-shangxia-20 d-wenzi-hui" v-if="noMoreData">
  									  <uv-divider text="没有更多数据了"></uv-divider>
  									</view>

								</uv-row>
						</view>

					</view>

				</view>
				<!--下面内容-->


			</view>

			<view class="d-clear"></view>
		
		</view>
		<!--底部-->
	    <view class="d-kuan-juzhong">
			<view class="d-kuan d-dibu-50">
				<view class="d-dibu-juzhong d-buhuanhang">
					<!--上传图片-->
					<view class="example-body ">
						
						<uv-upload
							:fileList="fileList1"
							name="1"
							multiple
							leixing="1"
							:maxCount="9"
							@afterRead="afterRead"
							@delete="deletePic"
							@clickPreview="clickPreview"
							@insertImage="handleInsertImage"
							accept="image/*,video/*"
							:previewFullImage="true"
						></uv-upload>
						
					</view>
					<uv-upload
						:fileList="fileList_yinpin1"
						name="1"
						multiple
						:maxCount="1"
						leixing="2"
						@afterRead="afterRead_yinpin"
						@delete="delete_yinpin"
						@clickPreview="clickPreview_yinpin"
						@insertImage="handleInsertImage_yinpin"
						@insertAudio="handleInsertAudio_yinpin"
						accept="image/*,video/*"
						:previewFullImage="true"
					></uv-upload>
				</view>
				
				<view class="d-dibu-juzhong ">
					<uv-row  gutter="15">
						<uv-col span="4">
							<view class="">
								
							</view>
						</uv-col>
						<uv-col span="4">
							<view class="">
								<uv-button type="primary"  text="确认修改" @click="postEdit_api(1)"></uv-button>
							</view>
						</uv-col>
						<uv-col span="4">
							<view class="">
								<uv-button type="primary"  text="确认后返回帖子" @click="postEdit_api(2)"></uv-button>
							</view>
						</uv-col>
					</uv-row>

				</view>

			</view>

		</view>
		
		<!--view class="d-kuan d-waigao-20 d-bianhua-10 pc-yincang"></view-->

		<!--view class="d-clear pc-yincang"></view-->
		<!--view class="d-weibu pc-yincang">
			<Dweibu></Dweibu>
		</view-->

	</view>
	
</template>

<script>
    import Api from '@/utils/api.js';
	import ZhishiApi from '@/utils/zhishi_api.js';
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
    //引入组件 d-toubu
    import DToubu from '@/components/d-toubu/d-toubu.vue'
	import Ddaohang from '@/components/d-daohang/d-daohang.vue'
	import Dweibu from '@/components/d-weibu/d-weibu.vue'

	import ccTwoCate from '@/uni_modules/cc-twoCate/components/cc-twoCate/cc-twoCate.vue'

    import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
	//import '@wangeditor/editor/dist/css/style.css' // 引入 css (移至最后提高优先级)
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
	
	
	
	export default {
		setup() {
			// 编辑器实例，必须用 shallowRef
			const editorRef = shallowRef(null)
			// 内容 HTML
			const valueHtml = ref('')
			// 编辑器配置
			
			// 工具栏配置
			// 工具栏配置 - 移除上传图片按钮
			const toolbarConfig = {
				
			}
			// 排除不需要的菜单
			toolbarConfig.excludeKeys = [
				//'headerSelect',
				'lineHeight', //行高
				'todo', // 待办
				'emotion', //表情
				'fontFamily',//字体

				'underline',
				'italic',
				'group-more-style', // 排除菜单组
				'group-image', // 排除图片上传
				'group-video',  // 排除视频上传
				'undo',
				'redo',
				'fullScreen',
				'divider',
				'group-indent',


			]
			const editorConfig = {
				placeholder: '请输入内容...',
				MENU_CONF: {
					// 配置上传图片
					image: {
						uploadType: 'custom',
						customUpload: () => {}, // 占位，实际不使用
					},
					// 配置上传视频
					video: {
						uploadType: 'custom',
						customUpload: () => {}, // 占位，实际不使用
					}
				}
			}
			// 模拟 ajax 异步获取内容
			onMounted(() => {
				setTimeout(() => {
				// 将neirong的值赋给valueHtml
				valueHtml.value = neirong.value
				}, 1500)
			})
			// 定义响应式变量 neirong
			const neirong = ref('')
			const title_20 = ref('')

			// 编辑器创建时的回调函数
			const handleCreated = (editor) => {
				editorRef.value = editor // 记录 editor 实例
				console.log('editor is created', editor);
				// 检查编辑器方法是否存在
				console.log('编辑器支持insertImage:', typeof editor.insertImage === 'function');
				console.log('编辑器支持cmd.do:', editor.cmd && typeof editor.cmd.do === 'function');
			}
			const handleChange = (editor) => {
			    //console.log('change:', editor.getHtml())
				neirong.value = editor.getHtml();
				title_20.value = editor.getText();
				
				//console.log('change:', editor.getAllMenuKeys())
			}
			const handleFocus = (editor) => {
			    console.log('focus', editor)
			}

			
			// 处理插入图片到编辑器
			const handleInsertImage = (event) => {
				console.log('handleInsertImage事件触发', event);
				// 获取图片URL
				const imageUrl = event.url || event.thumb;
				console.log('图片URL:', imageUrl);
				if (imageUrl) {
					// 检查编辑器实例
					if (editorRef.value) {
						try {
							// 确保编辑器有焦点
							editorRef.value.focus();

							// 延迟执行插入，确保焦点已获取
							setTimeout(() => {
								// 使用insertImage方法（如果可用）
								if (typeof editorRef.value.insertImage === 'function') {
									editorRef.value.insertImage(imageUrl);
									console.log('使用insertImage方法在光标位置插入图片成功');
								} else if (editorRef.value.cmd && typeof editorRef.value.cmd.do === 'function') {
									// 确保插入到正确的位置
									const imageHtml = `<img src="${imageUrl}" style="max-width:100%;height:auto;" />`;
									editorRef.value.cmd.do('insertHTML', imageHtml);
									console.log('使用cmd.do在光标位置插入图片成功');
								} else {
									console.error('编辑器实例不支持在光标位置插入图片的方法');
									// 尝试其他可能的插入方法
									try {
										const imageHtml = `<img src="${imageUrl}" style="max-width:100%;height:auto;" />`;
										
										// 检查是否有pasteHTML方法
										if (typeof editorRef.value.pasteHTML === 'function') {
											editorRef.value.pasteHTML(imageHtml);
											console.log('使用pasteHTML方法在光标位置插入图片成功');
										} 
										// 检查是否有insert方法
										else if (editorRef.value.insert) {
											editorRef.value.insert(imageHtml);
											console.log('使用insert方法在光标位置插入图片成功');
										} 
										// 检查是否有document属性并尝试execCommand
										else if (editorRef.value.document && typeof editorRef.value.document.execCommand === 'function') {
											editorRef.value.document.execCommand('insertHTML', false, imageHtml);
											console.log('使用document.execCommand在光标位置插入图片成功');
										} 
										// 检查是否有setContent方法
										else if (typeof editorRef.value.setContent === 'function') {
											const currentContent = editorRef.value.getContent() || '';
											editorRef.value.setContent(currentContent + imageHtml);
											console.log('使用setContent方法在内容末尾插入图片成功');
										} 
										// 检查是否有append方法
										else if (typeof editorRef.value.append === 'function') {
											editorRef.value.append(imageHtml);
											console.log('使用append方法在内容末尾插入图片成功');
										} 
										// 检查是否有addContent方法
										else if (typeof editorRef.value.addContent === 'function') {
											editorRef.value.addContent(imageHtml);
											console.log('使用addContent方法在内容末尾插入图片成功');
										} 
										// 检查是否可以直接访问DOM
										else if (editorRef.value.el && editorRef.value.el.innerHTML) {
											editorRef.value.el.innerHTML += imageHtml;
											console.log('直接操作DOM在内容末尾插入图片成功');
										} 
										// 所有方法都失败，直接在末尾插入
										else {
											console.log('所有插入方法都不支持，直接在末尾插入');
											const imageHtml = `<p><img src="${imageUrl}" style="max-width:100%;height:auto;" /></p>`;
											editorRef.value.setHtml(editorRef.value.getHtml() + imageHtml);
											console.log('在内容末尾插入图片成功');
											/*uni.showToast({
												title: '图片已插入到内容末尾',
												icon: 'none'
											});*/
										}
									} catch (e) {
										console.error('所有插入方法都失败:', e);
										// 备选方案：在内容末尾插入
										const imageHtml = `<p><img src="${imageUrl}" style="max-width:100%;height:auto;" /></p>`;
										editorRef.value.setHtml(editorRef.value.getHtml() + imageHtml);
										console.log('在内容末尾插入图片成功');
										// 显示提示给用户
										uni.showToast({
											title: '无法在光标位置插入图片，已在内容末尾插入',
											icon: 'none'
										});
									}
									return;
									
								}
							}, 100);
						} catch (error) {
							console.error('插入图片时发生错误:', error);
							uni.showToast({
								title: '插入图片失败: ' + error.message,
								icon: 'none'
							});
						}
					} else {
						console.error('编辑器实例不存在');
						uni.showToast({
							title: '编辑器尚未准备好，请稍后再试',
							icon: 'none'
						});
					}
				} else {
					console.error('未找到图片URL');
					uni.showToast({
						title: '未找到图片URL',
						icon: 'none'
					});
				}
			}

			// 视频类型检测函数
			const getVideoType = (url) => {
				const ext = url.split('.').pop().toLowerCase();
				const videoTypes = {
					'mp3': 'video/mp3',
					'mp4': 'video/mp4',
					'webm': 'video/webm',
					'ogg': 'video/ogg',
					'mov': 'video/quicktime',
					'avi': 'video/x-msvideo',
					'wmv': 'video/x-ms-wmv'
				};
				return videoTypes[ext] || null;
			};

			// 提取视频封面函数
			const extractVideoCover = (videoUrl) => {
				return new Promise((resolve) => {
					const video = document.createElement('video');
					video.src = videoUrl;
					video.crossOrigin = 'anonymous';
					video.addEventListener('loadedmetadata', () => {
						// 视频加载元数据后，跳转到第1秒处（避免黑屏）
						video.currentTime = 1;
						video.addEventListener('seeked', () => {
							const canvas = document.createElement('canvas');
							canvas.width = video.videoWidth;
							canvas.height = video.videoHeight;
							const ctx = canvas.getContext('2d');
							ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
							// 将canvas转换为图片URL
							const coverUrl = canvas.toDataURL('image/jpeg');
							resolve(coverUrl);
						}, { once: true });
					});
					// 错误处理
					video.addEventListener('error', () => {
						console.error('视频封面提取失败');
						resolve(null);
					}, { once: true });
				});
			};

			// 处理插入视频到编辑器
			const handleInsertVideo_yinpin = async (event) => {

				console.log('handleInsertVideo事件触发', event);
				// 获取视频URL
				const videoUrl = event.url || event.tempFilePath || '';
				console.log('视频URL:', videoUrl);
				let coverUrl = null;
				if (videoUrl) {
					// 提取视频封面
					coverUrl = await extractVideoCover(videoUrl);
					console.log('视频封面URL:', coverUrl);

					// 检查编辑器实例
					if (editorRef.value) {
						try {
							// 确保编辑器有焦点
							editorRef.value.focus();

							// 延迟执行插入，确保焦点已获取
							setTimeout(() => {
								// 使用insertVideo方法（如果可用）
								if (typeof editorRef.value.insertVideo === 'function') {
									// 如果支持封面参数，则传入封面URL
									if (coverUrl) {
										editorRef.value.insertVideo(videoUrl, { poster: coverUrl });
									} else {
										editorRef.value.insertVideo(videoUrl);
									}
									console.log('使用insertVideo方法在光标位置插入视频成功');
								} else if (editorRef.value.cmd && typeof editorRef.value.cmd.do === 'function') {
									// 确保插入到正确的位置
									const videoHtml = coverUrl ? 
										`<video src="${videoUrl}" poster="${coverUrl}" controls style="max-width:100%;height:auto;"></video>` : 
										`<video src="${videoUrl}" controls style="max-width:100%;height:auto;"></video>`;
									editorRef.value.cmd.do('insertHTML', videoHtml);
									console.log('使用cmd.do在光标位置插入视频成功');
								} else {
									console.error('编辑器实例不支持在光标位置插入视频的方法');
									// 尝试其他可能的插入方法
									try {
										// 构建带封面的视频HTML
										const videoType = getVideoType(videoUrl);
										let videoHtml = coverUrl ? 
											`<video src="${videoUrl}" poster="${coverUrl}" ${videoType ? `type="${videoType}"` : ''} controls style="max-width:100%;height:auto;"></video>` : 
											`<video src="${videoUrl}" ${videoType ? `type="${videoType}"` : ''} controls style="max-width:100%;height:auto;"></video>`;
										
										// 检查是否有pasteHTML方法
										if (typeof editorRef.value.pasteHTML === 'function') {
											editorRef.value.pasteHTML(videoHtml);
											console.log('使用pasteHTML方法在光标位置插入视频成功');
										} 
										// 检查是否有insert方法
										else if (editorRef.value.insert) {
											editorRef.value.insert(videoHtml);
											console.log('使用insert方法在光标位置插入视频成功');
										} 
										// 检查是否有document属性并尝试execCommand
										else if (editorRef.value.document && typeof editorRef.value.document.execCommand === 'function') {
											editorRef.value.document.execCommand('insertHTML', false, videoHtml);
											console.log('使用document.execCommand在光标位置插入视频成功');
										} 
										// 检查是否有setContent方法
										else if (typeof editorRef.value.setContent === 'function') {
											const currentContent = editorRef.value.getContent() || '';
											editorRef.value.setContent(currentContent + videoHtml);
											console.log('使用setContent方法在内容末尾插入视频成功');
											/*uni.showToast({
												title: '视频已插入到内容末尾',
												icon: 'none'
											});*/
										} 
										// 所有方法都失败，直接在末尾插入
										else {
											console.log('所有插入方法都不支持，直接在末尾插入');
											// 添加视频格式检查和type属性
											const videoType = getVideoType(videoUrl);
											const videoHtmlWithType = videoType ? 
												`<p><video src="${videoUrl}" type="${videoType}" controls style="max-width:100%;height:auto;"></video></p>` : 
												`<p><video src="${videoUrl}" controls style="max-width:100%;height:auto;"></video></p>`;
											editorRef.value.setHtml(editorRef.value.getHtml() + videoHtmlWithType);
											console.log('在内容末尾插入视频成功');
											/*uni.showToast({
												title: '视频已插入到内容末尾',
												icon: 'none'
											});*/
										}
									} catch (e) {
										console.error('所有插入方法都失败:', e);
										// 备选方案：在内容末尾插入
										const videoHtml = `<p><video src="${videoUrl}" controls style="max-width:100%;height:auto;"></video></p>`;
										editorRef.value.setHtml(editorRef.value.getHtml() + videoHtml);
										console.log('在内容末尾插入视频成功');
										// 显示提示给用户
										uni.showToast({
											title: '无法在光标位置插入视频，已在内容末尾插入',
											icon: 'none'
										});
									}
									return;
								}
							}, 100);
						} catch (error) {
							console.error('插入视频时发生错误:', error);
							uni.showToast({
								title: '插入视频失败: ' + error.message,
								icon: 'none'
							});
						}
					} else {
						console.error('编辑器实例不存在');
						uni.showToast({
							title: '编辑器尚未准备好，请稍后再试',
							icon: 'none'
						});
					}
				} else {
					console.error('未找到视频URL');
					uni.showToast({
						title: '未找到视频URL',
						icon: 'none'
					});
				}
			}

			return {
				editorRef,
				valueHtml,
				neirong,
				title_20,
				mode: 'default', // 或 'simple'
				toolbarConfig,
				editorConfig,
				handleCreated,
				handleChange,
				handleFocus,
				handleInsertImage,
				handleInsertVideo_yinpin

			}
			
		},
		data() {
		return {
			// 音频预览相关
			isPlaying: false,
			innerAudioContext: null,
			
			leftNavHeight: '', // 默认高度

				ftNavHeight: '500rpx', // 默认高度
				
                rightColWidth: '300px', // 默认宽度
				rightColLeft: '0px', // 添加这个属性
				imageSize:'',
			
     		    width: 0,
        		height: 0,
				denglu_xianshi:0, // 登录显示
				kuan_shu: 8, //格大小
				swiperHeight: '250',
				gao: '20', //图片高度
				id: '', // 存储从全局获取的id",
				title:'', // 存储从全局获取的title",
				quanzizhi:0, // 全选
				xuanzequan_gao:0,
				categoryList:[],
				dataList:[],
				currentTwo:0,
				quan_daohang_list:[], // 圈子导航列表
				quan_list:[], // 圈子列表
				erjiindex:'',//当前激活的二级菜单索引
				activeIndex: -1, // 当前激活的一级菜单索引
				xuanzezhi:0, // 列表
				currentPage: 1, //下拉加载
    			pageSize: 12, //下拉加载
    			isLoading: false, //下拉加载
    			noMoreData: false, //下拉加载

				//上传图片
				fileList1: [],//图片存储
				fabuid:{},//发布id
				uptu:[],
				//上传音频
				fileList_yinpin1: [],//音频存储
				fabuid_yinpin:{},//发布id
				up_yinpin:[],
				neirong_data:[],
			}
		},
		components: {
  		    DToubu,
			Ddaohang,
			Dweibu,
			Editor, 
			Toolbar,
			ccTwoCate
  		},
		// 组件销毁时，也及时销毁编辑器
      
		mounted() {
			//var m = this.$store.state;
			//console.log('mmmm',m);
			
    	    this.setLeftNavHeight();
			this.getRightColWidth(); // 添加这行
    	    // 添加窗口大小变化监听
    	    window.addEventListener('resize', this.setLeftNavHeight);
			window.addEventListener('resize', this.getRightColWidth); // 添加窗口大小变化监听
			var e = this;
			//this.onImageLoad(e);
    	},
    	beforeDestroy() {
    	    // 移除监听
    	    window.removeEventListener('resize', this.setLeftNavHeight);
			window.removeEventListener('resize', this.getRightColWidth); // 添加这行
    	},
		onShow() {
			//var m = this.$store.state;
			//this.id = getApp().globalData.currentId || '';
			this.title = getApp().globalData.title || '';
			console.log('获取到的id:', this.id);
			this.quan(this.id,this.title);
			this.getFabuid_api();
			
			// 可以在这里使用id进行其他操作
			// 使用后可以选择清除全局变量，避免下次进入时仍有值
			// getApp().globalData.currentId = null;
		},
		onLoad() {
			// 获取url参数的id
			var id = this.$route.query.id;
			var cid = this.$route.query.cid;

			//打印id
			console.log('获取到的id:', id);
			console.log('获取到的cid:', cid);


			if(id){
				this.id = id;
				this.cid = cid;
				this.getEdit_api();
			}

			
		},
		computed: {
			yidenglu() {
				return (this.$store.state.memberuid && this.$store.state.keycode) ? 1 : 0;
			},
			touxiang() {
				return this.$store.state.member? this.$store.state.member.avatar : '';
			},
		    name1() {
				return this.$store.state.member ? this.$store.state.member.name : '';
			}
		},
		methods: {
			// 音频预览方法
			clickPreview_yinpin(event) {
				console.log('音频预览事件触发', event);
				// 获取音频索引
				const index = event.index;
				// 获取音频文件
				const audioFile = this.fileList_yinpin1[index];
				if (!audioFile || !audioFile.url) {
					uni.showToast({
						icon: 'none',
						title: '音频文件不存在'
					});
					return;
				}
				
				// 创建或复用音频上下文
				if (!this.innerAudioContext) {
					this.innerAudioContext = uni.createInnerAudioContext();
					// 监听播放结束
					this.innerAudioContext.onEnded(() => {
						this.isPlaying = false;
						console.log('音频播放结束');
					});
					// 监听错误
					this.innerAudioContext.onError((err) => {
						this.isPlaying = false;
						console.error('音频播放错误:', err);
						uni.showToast({
							icon: 'none',
							title: '播放失败: ' + err.errMsg
						});
					});
				}
				
				// 如果当前播放的是同一个音频，则切换播放/暂停状态
				if (this.innerAudioContext.src === audioFile.url) {
					if (this.isPlaying) {
						this.innerAudioContext.pause();
						this.isPlaying = false;
						uni.showToast({
							icon: 'none',
							title: '已暂停'
						});
					} else {
						this.innerAudioContext.play();
						this.isPlaying = true;
						uni.showToast({
							icon: 'none',
							title: '正在播放'
						});
					}
				} else {
					// 播放新的音频
					this.innerAudioContext.stop();
					this.innerAudioContext.src = audioFile.url;
					this.innerAudioContext.play();
					this.isPlaying = true;
					uni.showToast({
						icon: 'none',
						title: '正在播放'
					});
				}
			},
			
			// 切换播放/暂停
			togglePlay() {
				if (this.isPlaying) {
					this.innerAudioContext.pause();
				} else {
					this.innerAudioContext.play();
				}
				this.isPlaying = !this.isPlaying;
			},
			
			// 调整播放进度
			seekAudio() {
				this.innerAudioContext.seek(this.progress);
				this.currentTime = this.progress;
			},
			
			// 格式化时间显示
			formatTime(time) {
				const minutes = Math.floor(time / 60);
				const seconds = Math.floor(time % 60);
				return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			},
			
			//图片
			onImageLoad(e, index) {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowHeight = systemInfo.windowWidth;
				if(windowHeight >=920){
					var gao = 30;
					
				} else {
					var gao = 0;

				}


				this.$nextTick(() => {
        		    const query = uni.createSelectorQuery().in(this);
        		    query.select('#tupian-'+index).boundingClientRect(data => {
        		        if (data && data.width > 0 && data.height > 0) {
        		            this.$set(this.haibao_data[index], 'imageSize', {
        		                width: data.width,
        		                height: data.height + gao
        		            });
							console.log('图片尺寸:', this.haibao_data[index].imageSize);
        		        } else {
        		            console.warn(`图片${index}尺寸获取失败`);
        		            this.$set(this.haibao_data[index], 'imageSize', {
        		                width: 300,
        		                height: 200
        		            });
        		        }
        		    }).exec();
        		});

    		},
			getRightColWidth() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowWidth = systemInfo.windowWidth;
				var d = this;

                this.$nextTick(() => {
				if(windowWidth >=920){
					d.gao = 20;
					d.kuan_shu = 8;
					d.swiperHeight = '250';
				} else {
					d.gao = 10;
					d.kuan_shu = 12;
					d.swiperHeight = '120';

				}
				console.log('窗口高度:', windowWidth);

                 const query = uni.createSelectorQuery().in(this);
                 query.select('#youbiankuan').boundingClientRect(rect => {
                   if (rect) {
                     /*this.rightColWidth = `${rect.width+20}px`;
                     console.log('右侧列宽度:', this.rightColWidth);*/
					 	this.rightColWidth = `${rect.width-80}px`;
                    	this.rightColLeft = `${rect.left}px`; // 计算左侧位置
                    	console.log('右侧列位置:', this.rightColWidth);
                   }
                 }).exec();
               });
            },

			//首页
			shouye(){
				uni.navigateTo({
					url: '/pages/index/index',
					fail: (err) => {
						console.error('跳转失败:', err)
					}
				})
			},
			
			setLeftNavHeight() {
        	    // 获取系统信息
        	    const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowHeight = systemInfo.windowHeight;
        	    const headerHeight = 130; // 头部高度估计值
        	    const calculatedHeight = windowHeight - headerHeight;
				
        	    // 设置左边导航高度
        	    this.leftNavHeight = `${calculatedHeight}px`;

				const quan_gao = 60; // 头部高度估计值
        	    const quan_gao_1 = windowHeight - quan_gao;
				this.xuanzequan_gao = `${quan_gao_1}px`;
        	},
			
			handleLoginSuccess() {
  			  this.$forceUpdate();
  			},
			
			
			
			denglu_fabu(){
				if(this.yidenglu == 0){
					this.denglu_xianshi = 1;
				} else {
					this.denglu_xianshi = 0;	
				}
				
				console.log('发布登录',this.denglu_xianshi);
				
			},
			// 更新判断是否登录
			handleUpdateDengluxianshi(value) {
			  this.denglu_xianshi = value;
			  console.log('关闭登录',this.denglu_xianshi);
			},
			xuanze_quan(){
				// 点击切换状态：1->0, 0->1
				this.quanzizhi = this.quanzizhi === 1 ? 0 : 1;
				if(this.quanzizhi == 1){
					this.quan_daohang_api(); // 圈子导航
					var e = this;
			        this.quan_list_api(e,false);
				}

				
			},
			yiji2(index) {
				this.xuanzezhi = 0;
				
				console.log(this.xuanzezhi);
    		  // 切换激活的一级菜单
			  setTimeout(() => {

    			  	this.activeIndex = index;
    			  	// 根据激活的一级菜单显示对应的二级菜单
				  	if(index.id == 0){
						this.erjidata = [];
				  	}else{
						this.erjidata = this.quan_daohang_list[index.index].son;
				  	}
				  	const data = {
						  categories:index.id,
						  page: 1 // 重置页码
				  	}
					this.currentPage = 1; // 重置页码
					this.noMoreData = false; // 重置无更多数据标志
				  	this.quan_list_api(data,false);
					  
				}, 300);
    		  
			  
    		},
			erji2(index) {
				this.xuanzezhi = index.index;
    		  // 切换激活的二级菜单
    		  this.erjiindex = index.id;
			  this.activeIndex = index;

			  const data = {
				  categories:index.id,
				  page: 1 // 重置页码
			  }
			    this.currentPage = 1; // 重置页码
				this.noMoreData = false; // 重置无更多数据标志
				this.quan_list_api(data,false);
				console.log('二级分类：',index);

    		},
			//获取数据
			getQuan(){
				// 选择圈子数据
				
				var get_data = getRequest(ZhishiApi.getXuanze_quan());

				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						// 转换时间戳为日期格式
						var daohang_list = res.data ? res.data.data[0].daohang_list : [];
						var quan_list = res.data ? res.data.data[0].quan_list : [];
						console.log('选择圈子',quan_list);

						this.categoryList = daohang_list;
						this.dataList = quan_list;
						
					}
				})

			},
			// 导航接口
			quan_daohang_api(){
				var get_data = getRequest(ZhishiApi.getZhishi_daohang());
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						// 转换时间戳为日期格式
						//var list = res.data ? res.data.data : {};
						var list = res.data && res.data.data ? res.data.data.lisi2 : [];
						// 在 list 前面添加插入一个新的数据“首页”
						
        				this.quan_daohang_list = list;
						console.log(list);
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
			},
			//列表接口
			quan_list_api(data, isLoadMore = false){
				if (!data) data = {};
				if (!data) data = {};
		  		if (!data.page) data.page = 1;
		  		if (!data.categories) data.categories = 0;
		  		if (!data.search) data.search = '';
				var get_data = getRequest(ZhishiApi.getZhishi_list(data));
				var res;	
				get_data.then(duixin_data => {
					res = duixin_data;	
					if(res.data.code) {
						// 转换时间戳为日期格式
						var list = res.data? res.data.data : {};
						//this.zhishi_list = list;
						if (isLoadMore) {
							// 加载更多时追加数据
							this.quan_list = [...this.quan_list, ...list];
							//this.quan_list = list;
        				} else {
        				  // 非加载更多时替换数据
        				  this.quan_list = list;
        				}	
						// 判断是否还有更多数据
						this.noMoreData = list.length < this.pageSize;
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
					this.isLoading = false;
				}).catch(() => {
    			  this.isLoading = false;
    			  if (isLoadMore) {
    			    this.currentPage--; // 加载失败时回退页码
    			  }
    			});
			},
			// 下拉加载更多
  			onReachBottom() {
  			  
  			},
			quan(id,title){
				if(id){
					this.id = id;
					this.title = '已选'+title;
					this.quanzizhi = 0;
				}else{
					this.id = '';
					this.title = '选择课程';
					this.quanzizhi = this.quanzizhi === 1 ? 0 : 1;
					this.quan_daohang_api(); // 导航
					var e = this;
			        this.quan_list_api(e,false);
				}
				console.log('圈子id',id+'圈子名称',title);

			},
			// 修改接口
			postEdit_api(leixing){
				// 确保从 Vuex 获取最新值
				const uid = this.$store.state.memberuid;
                const keycode = this.$store.state.keycode;
				
				// 如果id为空
				if(!this.id){
					uni.showToast({
						icon: 'none',
						title: '请选择圈子'
					});
					return;
				}
				var title = this.neirong_data.title;
				// 获取前30个文字
				// 过滤HTML标签，只保留纯文本
				var plainText = title ? title.replace(/<[^>]+>/g, '') : '';
				var shortTitle = plainText ? plainText.substring(0, 20) : '';
				
					// 上传图片
					let img = '';
					var jiugetu =this.fileList1;
					jiugetu.forEach(item=>{
						img+= '&data[tupian][id][]='+item.id+'&data[tupian][title][]=tupian'
					})

				
					// 上传音频
					
					let yinpin = '';
					var up_yinpin =this.fileList_yinpin1;
					up_yinpin.forEach(item=>{
						yinpin+= '&data[yinpin][id][]='+item.id+'&data[yinpin][title][]=yinpin'
					})
					// 属性
					const shuxing = '&data[gongkai]='+this.neirong_data.gongkai+'&data[moshi]='+this.neirong_data.moshi;


				var datas = "is_ajax=1&data[title]="+title+"&data[neirong]="+this.neirong+"&cid="+this.id+img+yinpin+shuxing;
				var post_data = postRequest(ZhishiApi.getEdit_tie(uid,keycode,this.id),datas);
				var res;
				post_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						});
						this.neirong = '';
						// 修改成功后跳转到当前圈子页面
						
						if(leixing==2){
							uni.navigateTo({
								url: '/pages/ke/ke?id='+this.id+'&cid='+this.cid,

									success: () => {
									console.log('跳转成功');
								},
								fail: (err) => {
									console.error('跳转失败:', err);
									uni.showToast({
											title: '跳转失败，请重试',
											icon: 'none'
									});
								}
							});
						}
						
						
					} else {
						uni.showToast({
							icon: 'none',
							title: '发布失败'
						});
						
						
					}
				})
			},
		// 新增图片
		async afterRead(event) {
			var duixin = this; 
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				console.log('event',event); 
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					// 判断文件类型
					const isImage = item.type.startsWith('image/');
					const isAudio = item.type.startsWith('audio/');
					
					// 只处理图片和音频文件
					if (isImage || isAudio) {
						this[`fileList${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中',
							fileType: isImage ? 'image' : 'audio'
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: '不支持的文件类型，请上传图片或音频'
						})
					}
				})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url,1)
				const id = duixin.uptu.data.id;
				console.log('uptu',duixin.uptu.data.id); 
				let item = this[`fileList${event.name}`][fileListLen]
				// 更新文件列表状态
					const updatedItem = Object.assign(item, {
						status: 'success',
						message: '',
						url: result,
						id: id,
						fileType: item.fileType // 保留文件类型信息
					})
					this[`fileList${event.name}`].splice(fileListLen, 1, updatedItem)
					fileListLen++
					//打印更新后的文件列表
					console.log('更新后的文件列表',this[`fileList${event.name}`]);

					
					// 注释掉自动插入逻辑，根据用户需求取消自动插入
					// if (updatedItem.fileType === 'image') {
					// 	this.handleInsertImage({ url: result })
					// } else if (updatedItem.fileType === 'video') {
					// 	this.handleInsertVideo({ url: result })
					// }
				}
		},
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
		},
		//上传图片
		uploadFilePromise(url,leixing) {
			
			
			var duixin = this; 
			console.log('fabuidjiugetu',duixin.fabuid && duixin.fabuid.jiugetu); 
			const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
			if(leixing==1){
				// 图片上传
				var upid = duixin.fabuid && duixin.fabuid.yinpintu;
			} else if(leixing==2){
				// 视频上传
				var upid = duixin.fabuid && duixin.fabuid.yinpin;
			}

			
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: ZhishiApi.postTupians(uid,keycode)+'&fid='+upid, //
					filePath: url,
					name: 'file_data',
					formData: {
						is_ajax:1
					},
					success: (res) => {
						var duixin = this; 
						if(leixing==1){
							duixin.uptu = JSON.parse(res.data);
							//打印duixin.uptu
							console.log('duixin.uptu',duixin.uptu);
							// 假设接口返回的数据中有img_url字段包含图片URL
							// 使用正确的URL路径，并确保传递给handleInsertImage
							const imgUrl = duixin.uptu.data.url || '';
							console.log('服务器返回的图片URL:', imgUrl);
							setTimeout(() => {
								resolve(imgUrl)
							}, 1000)

						} else if(leixing==2){
							duixin.up_yinpin = JSON.parse(res.data);
							//打印duixin.uptu
							console.log('duixin.up_yinpin',duixin.up_yinpin);
							const yinpinUrl = duixin.up_yinpin.data.url || '';
							console.log('服务器返回的图片URL:', yinpinUrl);
							setTimeout(() => {
								resolve(yinpinUrl)
							}, 1000)
						}

						

						
						// 注释掉自动插入逻辑，根据用户需求取消自动插入
					// this.handleInsertImage({url: imgUrl});
						
						}
						
				});
			})
		},
		//发布id
		getFabuid_api(){
			var duixin = this; 
			var get_data = getRequest(ZhishiApi.getFabuid());
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						duixin.fabuid = res.data.data;
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
		},
		// 图片预览方法
		clickPreview(event) {
			console.log('clickPreview事件触发', event);
			// 获取当前点击的图片索引
			const index = event.index;
			// 获取所有图片的url数组
			const urls = this.fileList1.map(item => item.url);
			console.log('图片URL列表', urls);
			console.log('当前索引', index);
			// 调用uni-app的图片预览API
			uni.previewImage({
				urls: urls,
				current: index,
				success: function(res) {
					console.log('预览成功', res);
				},
				fail: function(err) {
					console.error('预览失败', err);
				}
			});
		},
		
		// 音频上传
		async afterRead_yinpin(event) {
			var duixin = this; 
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				console.log('event',event); 
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList_yinpin${event.name}`].length

				lists.map((item) => {
					// 判断文件类型
					const isImage = item.type.startsWith('image/');
					const isAudio = item.type.startsWith('audio/');
					
					// 只处理图片和音频文件
					if (isImage || isAudio) {
						this[`fileList_yinpin${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中',
							fileType: isImage ? 'image' : 'video'
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: '不支持的文件类型，请上传图片或音频'
						})
					}
				})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url,2)
				const id = duixin.up_yinpin.data.id;
				console.log('up_yinpin',duixin.up_yinpin.data.id); 
				let item = this[`fileList_yinpin${event.name}`][fileListLen]
				// 更新文件列表状态
					const updatedItem = Object.assign(item, {
						status: 'success',
						message: '',
						url: result,
						id: id,
						fileType: item.fileType // 保留文件类型信息
					})
					this[`fileList_yinpin${event.name}`].splice(fileListLen, 1, updatedItem)

					fileListLen++
					
					// 注释掉自动插入逻辑，根据用户需求取消自动插入
					// if (updatedItem.fileType === 'image') {
					// 	this.handleInsertImage({ url: result })
					// } else if (updatedItem.fileType === 'video') {
					// 	this.handleInsertVideo({ url: result })
					// }
				}
				//console.log('_yinpin1',this.fileList_yinpin1); 
		},
		// 删除视频
		delete_yinpin(event) {
			this[`fileList_yinpin${event.name}`].splice(event.index, 1)
		},
		/*postEdit_api(){
			console.log('postEdit_api');
		},*/
		//获取修改内容
		getEdit_api(){
			const uid = this.$store.state.memberuid;
            const keycode = this.$store.state.keycode;
			//获取url参数id和cid
			var id = this.$route.query.id;
			var cid = this.$route.query.cid;
			//打印id和cid
			console.log('id',id);
			console.log('cid',cid);
			var get_data = getRequest(ZhishiApi.getEdit_tie(uid,keycode,id));
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						// 转换时间戳为日期格式
						//var list = res.data ? res.data.data : {};
						var list = res.data && res.data.data && res.data.data.neirong  ? res.data.data.neirong.neirong : [];
						var tupian_list = res.data && res.data.data && res.data.data.neirong  ? res.data.data.neirong.tupian : [];
						var yinpin_list = res.data && res.data.data && res.data.data.neirong  ? res.data.data.neirong.yinpin : [];
						var neirong_data = res.data && res.data.data   ? res.data.data.data : [];
						// 标题
						this.neirong_data = neirong_data;

						// 获取到的 list 数据 直接赋值给 setup()里面的const neirong = ref('')
						// 将数据赋值给setup中的neirong变量
						// 调用handleChange方法设置neirong的值
						if (this.handleChange) {
							// 创建一个模拟的editor对象，包含getHtml方法
							const mockEditor = {
								getHtml: () => list,
								getText: () => list
							};
							this.handleChange(mockEditor);
						}
						this.fileList1 = tupian_list; //图片
						this.fileList_yinpin1 = yinpin_list; //音频
						//打印
						console.log('tupian_list',tupian_list);

        				// this.quan_daohang_list = list;
						//console.log('获取到的 list 数据',list);
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
		}

	}
}
</script>



<style scoped>
    .d-xuanze-0 {
		position: relative; /* 建立定位上下文 */
	}

	.d-xuanze-1 {
		position: absolute; /* 相对于父元素定位 */
		top: 0; /* 顶部对齐 */
		left: 0; /* 左侧对齐 */
		width: 100%; /* 宽度填满父元素 */
		background-color: #ffffff;
	}

	.d-dibu-50 {
		position: fixed;
		
		bottom: 0px;
		left: 0;
		right: 0;
		z-index: 999;
		/*background-color: #fff;*/ /* 可以根据需要调整背景色 */
		padding: 10px 0; /* 可以根据需要调整内边距 */
	}
	.d-dibu-juzhong {
		/* 最大宽 1500px */
		padding-left: 10px;
		padding-right: 10px;
		max-width: 1390px;
		margin: 0 auto; /* 左右居中 */

		
		/*background-color: #8f8f94;*/

	}
	.scroll-fix {
		overflow-y: hidden;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		
		background-color: #f3f3f3;
		/*padding-top: 70px;
		margin-bottom: 70px;*/
		/*height: 100vh;*//* 添加全屏 */
		
		box-sizing: border-box;
		overflow-x: hidden;
		

	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	/* 屏幕宽度大于786px时隐藏uni-page-head */
    @media (min-width: 786px) {
        uni-page-head {
            display: none !important;
            opacity: 0 !important;
            height: 0 !important;
            visibility: hidden !important;
        }
    }
	/*.d-daohang{
		
		width: 600rpx;
	}*/
	/* 添加在style部分 */
	.d-daohang-zuo {
    position: fixed;
    left: 0;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #f5f5f5;
    z-index: 100;
	box-shadow: 2px 0 5px rgba(177, 177, 177, 0.1);
  }
  
  .d-daohang-you {
    position: fixed;
    left: 180rpx;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #fff;
    z-index: 100;
    box-shadow: 2px 0 5px rgba(0,0,0,0.1);
  }
   
   
   
   
   
   
   
   
   
 
   
  .d-erji-item {
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 20rpx;
   /* border-bottom: 1px solid #f0f0f0;*/
  }
  
  .d-erji-item:active {
    background: #f5f5f5;
  }
  .you-guding {
	position: fixed;
	top: 0; /* 根据头部高度调整 */
	/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
	transition: all 0.3s ease;
}
/* 大于786px时的样式 */
@media screen and (min-width: 1024px) {
	.d-bianhua-10 {
		padding: 30px;
	}
	.pc-zuo-520 {
		margin-left: 520rpx;
	}
	.you-guding {
		position: fixed;
			
		top: 60px; /* 根据头部高度调整 */
		/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
		transition: all 0.3s ease;
	}
		
	
}
	
.audio-preview-container {
  padding: 20px;
  text-align: center;
}

.audio-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.audio-controls {
  margin: 20px 0;
}

.audio-progress {
  margin-top: 20px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

</style>
